package com.cuiyongzhi.wechat.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

/**
 * ClassName: WeChatController
 * @Description: 前端用户微信配置获取
 * @author dapengniao
 * @date 2016年3月19日 下午5:57:36
 */
@Controller
@RequestMapping("/wechat")
public class WxLoginController {
	private static Logger logger = Logger.getLogger(WxLoginController.class);
	
	public static final String APPID="wx8fef29a788ea9b53";
    public static final String APPSECRET="6ad4b1b9c7c0534dccac62e2b60b27da";
	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/auth/login")
	@ResponseBody
	public void wxlogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
		logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +" >>>>>>>>>>微信授权登录.....................");
		
		String backUrl="https://4f2ac6b3.ngrok.io/wechat/wechat/callBack";
        /**
        *这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
        **/
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8fef29a788ea9b53"+
			        "&redirect_uri=" + URLEncoder.encode(backUrl,"UTF-8")+
			        "&response_type=code" +
			        "&scope=snsapi_userinfo" +
			        "&state=STATE#wechat_redirect";
		response.sendRedirect(url);
	}
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	@RequestMapping("/callBack")
	@ResponseBody
	public Object wxCallBack(HttpServletRequest request,HttpServletResponse response) throws IOException {
		logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +" >>>>>>>>>>授权回调.....................");
		
		System.out.println("hahah");
        String code = request.getParameter("code");
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8fef29a788ea9b53"+
                "&secret=6ad4b1b9c7c0534dccac62e2b60b27da"+
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject = doGetJson(url);
        String openid=jsonObject.getString("openid");
        String token=jsonObject.getString("access_token");
        String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=" +token+
                "&openid=" +openid+
                "&lang=zh_CN";
        JSONObject userInfo = doGetJson(infoUrl);
        return userInfo;
	}
	
    public static JSONObject doGetJson(String url) throws IOException {
        JSONObject jsonObject=null;
        DefaultHttpClient defaultHttpClient=new DefaultHttpClient();
        HttpGet httpGet=new HttpGet(url);
        HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
        HttpEntity httpEntity=httpResponse.getEntity();
        if(httpEntity!=null){
            String result= EntityUtils.toString(httpEntity,"UTF-8");
            jsonObject = JSONObject.parseObject(result);
            System.out.println("jsonObject:  "+jsonObject);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }
}
